package main.java.com.demo;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JsoupTool {
    public static String getBody(String url) {
        String body=null;
        try {
            Connection.Response response = Jsoup.connect(url).execute();
            body=response.body();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }

    public static Document getDocument(String url) {
        Document document=null;
        Connection connection = Jsoup.connect(url);
        try {
            document=connection.get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return document;
    }

    public static Elements getElements(String url, String cssQuery) {
        Document document=getDocument(url);
        if (document==null) {
            return null;
        }
        Elements elements=document.select(cssQuery);
        return elements;
    }

    public static Elements getElements(Document document, String cssQuery) {
        Elements elements=document.select(cssQuery);
        return elements;
    }

    public static List<String> getHrefs(Elements elements) {
        List<String>list=new ArrayList<>();
        for(Element element: elements) {
            String href=element.attr("href");
            list.add(href);
        }
        return list;
    }

    public static List<String> getTexts(Elements elements) {
        List<String>list=new ArrayList<>();
        for(Element element: elements) {
            String href=element.text().trim();
            list.add(href);
        }
        return list;
    }
}
